<?php
namespace App\Http\Controllers\Api;

use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\ApiToken;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Mews\Captcha\Captcha;


class Guest extends Controller
{


    /**
     * 登入
     * code 验证码
     * key  验证码key
     */
    public function login(Request $req)
    {
        $credentials = request(['email', 'password']);
//        $credentials = ['email' => request('account'), 'password' => request('pwd')];
        if (!$token = auth()->attempt($credentials)) {
//            return response()->json(['error' => 'Unauthorized'], 401);
            return $this->resFail('用户名或密码错误');
        }
       /* if (!captcha_api_check($req->code ?: 1, $req->key)) {
            return $this->resFail('验证码有误');
        }*/

//        return $this->respondWithToken($token);
        return $this->resSuccess('操作成功', [
            'token'=> $token
        ]);


        return 1;
        if(Auth::attempt(['email' => request('account'), 'password' => request('pwd')]))
        {
            $user = Auth::user();
            $this->content['token'] = $user->createToken('Pi App')->accessToken;
            $status = 200;
        }
        else {
            $this->content['error'] = "未授权,用户名或密码错误";
            $status = 401;
        }
        return response()->json($this->content, $status);




        if (!$req->email || !$req->pwd) {
            return 'error';
        }

        $user = \App\User::where('email', $req->email)->first();
        if (!$user) {
            return 'password error';
        }

        $token = ApiToken::update($user);

        return $this->resSuccess('操作成功', [
            'token'=> $token
        ]);

    }


    /** 验证码
     *  @return key
     * @return img
     */
    public function captcha(Captcha $captcha)
    {

        return $this->resSuccess('操作成功',
//            captcha_src()
            $captcha->create('math', true)
        );
    }


    /**
     * 注册
     * @param Request $data
     * @return \App\Http\Controllers\HTTPResponse
     */
    public function reg(Request $data)
    {
        $res =  User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
        ]);

        return $this->resSuccess('操作成功', $res);
    }


    public function logout(Request $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
        ]);
    }




    protected function respondWithToken($token)
    {
        return response()->json([
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => auth()->factory()->getTTL() * 60
        ]);
    }

}